package com.example.testapp.activity.activity.study;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.example.testapp.R;
import com.example.testapp.activity.http.MHttpEntity;
import com.example.testapp.activity.model.ResponseWrapper;
import com.example.testapp.activity.model.SendDataEntity;
import com.google.gson.GsonBuilder;

import org.apache.http.util.EntityUtils;
import org.apache.http.ParseException;
import java.io.IOException;

/**
 * Created by l on 2016/8/1.
 */
public class WeaterActivity extends AppCompatActivity {

    public ResponseWrapper response; // 数据结构的对象
    public static final int succeed = 1;
    public static final int fail = 2;
    public static final int nonet = 3;
    public String normalDistrict;
    public String locationCity = "武汉";
    public LocationClient mLocationClient = null;
    public BDLocationListener  mListener;
    private ProgressDialog mDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_weater);
        initData();
    }

    private void initData() {
        showProgressDialog("自动定位中...");
        initBaiduMapLocation();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                    sendRequest();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void initBaiduMapLocation() {
        mLocationClient = new LocationClient(this);
        mListener = new MyLocationListener();
        mLocationClient.registerLocationListener(mListener);
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setIsNeedAddress(true);
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }

    private void showProgressDialog(String title) {
        mDialog = new ProgressDialog(this);
        mDialog.setCancelable(false);
        mDialog.setMessage(title + "....");
        mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mDialog.show();
    }

    private void sendRequest() {
        String getData = null;
        MHttpEntity mhe = null;
        try{
            SendDataEntity.setCity(normalDistrict);
            Log.e("TAG", normalDistrict + "==>>normalDistrict");
            mhe = MHttpEntity.sendHttpRequest(SendDataEntity.getData());
            if(mhe.getHentity() != null){
                getData = EntityUtils.toString(mhe.getHentity());
                GsonBuilder gson = new GsonBuilder();
                response = gson.create().fromJson(getData, ResponseWrapper.class);
                Log.i("TAG", response.getError() + "-->response.getError()");
                if(response.getError() == -3){
                    SendDataEntity.setCity(normalDistrict);
                    mhe = MHttpEntity.sendHttpRequest(SendDataEntity.getData());
                    if(mhe.getHentity() != null){
                        getData = EntityUtils.toString(mhe.getHentity());
                        Log.i("weather_info", getData + "-->getData");
                    }
                    if(response.getError() == -3){
                        SendDataEntity.setCity(locationCity);

                        mhe = MHttpEntity.sendHttpRequest(SendDataEntity.getData());
                        if(mhe.getHentity() != null){
                            Log.e("TAG", mhe.getHentity() + "==>>mhe.getHentity()");
                            getData = EntityUtils.toString(mhe.getHentity());
                        }
                    }
                }
                mhe.getMessage().obj = getData;
            }

        }catch (ParseException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        handler.sendMessage(mhe.getMessage()); // 使用Handler对网络状态做处理
    }

    /**
     * 对网络连接状态做处理
     */
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
             if(mDialog != null){
                 mDialog.dismiss();
             }
            if(msg != null){
                switch (msg.arg1){
                    case succeed: // 与服务器连接成功，则传递数据并跳转
                        Intent intent = new Intent(WeaterActivity.this, WeaterMainActivity.class);
                        if(msg.obj != null)
                        intent.putExtra("weather_data", (String) msg.obj);
                        intent.putExtra("normal_city", locationCity);
                        startActivity(intent);
                        finish();
                        break;
                    case fail: // 与服务器连接失败，弹出错误提示Toast
                        Toast.makeText(WeaterActivity.this, getString(R.string.net_fail), Toast.LENGTH_SHORT).show();
                        intent = new Intent(WeaterActivity.this, WeaterMainActivity.class);
                        intent.putExtra("weather_data", (String) msg.obj);
                        startActivity(intent);
                        finish();
                        break;
                }
            }
        }
    };

    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if(bdLocation != null){
                normalDistrict = bdLocation.getDistrict();
                locationCity = bdLocation.getCity();

                if(locationCity == null){
                    Toast.makeText(WeaterActivity.this, "定位失败，请检查网络", Toast.LENGTH_SHORT).show();
                }else{
                    String[] str = locationCity.split("市");
                    locationCity = str[0];
                    if("".equals(locationCity)){
                        Toast.makeText(WeaterActivity.this, "定位失败，默认为武汉", Toast.LENGTH_LONG).show();
                    }
                }
            }
        }
    }
}
